#include "QNode.h"

QNode::QNode(void)
{
    this->setID(0);
    this->setPos(QPointF(0,0));
    this->setPosDot(QPointF(0,0));
    this->setFixed(false);
    this->setDT(0.01);
    this->setAllowedSize(400,300);

    fx = 0;
    fy = 0;
}

QPointF QNode::getPos(void)
{
    return pos;
}
QPointF QNode::getPosDot(void)
{
    return posDot;
}

int QNode::getID(void)
{
    return id;
}

void QNode::calcMemPot(void)
{
    for (int i=0; i<nerveList.length(); ++i)
    {
        nerveList[i]->spreadMemPot();
    }
    for (int i=0; i<nerveList.length(); ++i)
    {
        nerveList[i]->rotMemPot();
    }
}
double QNode::getMemPot(int channel)
{
    return nerveList[channel]->getMemPot();
}

bool QNode::isFixed(void)
{
    return fixed;
}

void QNode::rotate(void)
{
    double mu=0.1;

    fx-=mu*(posDot.x());
    fy-=mu*(posDot.y());

    if (!fixed)
    {
        posDot+=QPointF(fx*dt,fy*dt);
        pos+=QPointF(posDot.x()*dt, posDot.y()*dt);
    }
    else
    {
        posDot = QPointF(0,0);
    }


    if (pos.x()<5)
    {
        pos = QPointF(5, pos.y());
        posDot = QPointF(-posDot.x(),posDot.y());
    }
    else if (pos.x()>w-5)
    {
        pos = QPointF(w-5, pos.y());
        posDot = QPointF(-posDot.x(),posDot.y());
    }

    if (pos.y()<27)
    {
        pos = QPointF(pos.x(), 27);
        posDot = QPointF(posDot.x(),-posDot.y());
    }
    else if (pos.y()>h-5)
    {
        pos = QPointF(pos.x(), h-5);
        posDot = QPointF(posDot.x(),-posDot.y());
    }

    emit posDotXChanged(posDot.x());
    emit posDotYChanged(posDot.y());
    emit posXChanged(pos.x());
    emit posYChanged(pos.y());

    fx = 0;
    fy = 0;
}

QList<QNerveTissue*> QNode::getNerveList(void)
{
    return nerveList;
}
QList<int> QNode::getSenderList(void)
{
    QList<int> list;
    for (int i=0; i<nerveList.length(); ++i)
    {
        if (nerveList[i]->isSender()) list << i;
    }
    return list;
}

void QNode::addXForce(double _fx)
{
    fx+=_fx;
}
void QNode::addYForce(double _fy)
{
    fy+=_fy;
}
void QNode::setPos(QPointF _pos)
{
    pos = _pos;

    emit posXChanged(pos.x());
    emit posYChanged(pos.y());
}
void QNode::setPosDot(QPointF _posDot)
{
    posDot = _posDot;
}
void QNode::setFixed(bool _fixed)
{
    fixed = _fixed;
    emit fixedStateChanged(fixed);
}
void QNode::setID(int _id)
{
    if (_id>=0) id = _id;
    emit idChanged(id);
}
void QNode::setDT(double _dt)
{
    if (_dt>0) dt = _dt;
    emit DTChanged(dt);
}

void QNode::setAllowedSize(double _w, double _h)
{
    if (_w>0) w = _w;
    if (_h>0) h = _h;
}

void QNode::addNerve(QNerveTissue* _nerve)
{
    nerveList << _nerve;
}
void QNode::setNerveList(QList<QNerveTissue*> _nerveList)
{
    if(nerveList != _nerveList)
    {
        nerveList = _nerveList;
        emit nerveListChanged(id);
    }
}
